<template>
  <DraggableModal
    :visible="props.showModal"
    width="1200px"
    :maskClosable="false"
    :title="props.title"
    :destroyOnClose="true"
    @cancel="modalCancelFn"
  >
    <div class="approval">
      <p>审批单名称:</p>
      <span class="approval-name"
        ><calendar-outlined style="margin-right: 5px" />{{ state.approvalSlipName }}
      </span>
    </div>

    <p class="partition" v-if="props.title === '生成审批单'">本次审批单包含如下样本</p>

    <vxe-table
      border
      ref="xTable"
      :column-config="{ resizable: true }"
      :loading="state.loading"
      :data="state.tableData"
      :edit-config="{ trigger: 'click', mode: 'row' }"
    >
      <vxe-column type="seq" title="序号" width="60" />
      <vxe-column field="serial" title="菌种号" />
      <vxe-column field="name" title="菌种名称" />
      <vxe-column field="usage" title="运出实验室用途" :edit-render="{}">
        <template #edit="{ row }">
          <a-input v-model:value="row.usage" placeholder="运出实验室用途" />
        </template>
      </vxe-column>
      <vxe-column field="couriers" title="运出人员（双人）" :edit-render="{}">
        <template #edit="{ row }">
          <a-input v-model:value="row.couriers" placeholder="运出人员（双人）" />
        </template>
      </vxe-column>
      <vxe-column field="destination" title="目的地" :edit-render="{}">
        <template #edit="{ row }">
          <a-input v-model:value="row.destination" placeholder="目的地" />
        </template>
      </vxe-column>
      <vxe-column field="checker" title="复核人" :edit-render="{}">
        <template #edit="{ row }">
          <a-input v-model:value="row.checker" placeholder="复核人" />
        </template>
      </vxe-column>
      <vxe-column field="comment" title="备注" :edit-render="{}">
        <template #edit="{ row }">
          <a-input v-model:value="row.comment" placeholder="备注" />
        </template>
      </vxe-column>
      <vxe-column field="createTime" title="创建时间" />
      <vxe-column field="lastInPerson" title="创建者" />
    </vxe-table>

    <template #footer>
      <Popconfirm title="确定保存吗？" @confirm="modalSaveFn(0)">
        <Button type="primary">保存</Button>
      </Popconfirm>
      <Popconfirm @confirm="modalSaveFn(1)">
        <template #title>
          <p>确认提交{{ state.approvalSlipName }}审批单吗?</p>
          <div>以快捷方式提交的审批单不可更改!!!</div>
        </template>
        <Button type="primary">一键提交</Button>
      </Popconfirm>

      <Button type="primary" @click="modalCancelFn">关闭</Button>
    </template>
  </DraggableModal>
</template>

<script setup lang="ts">
import { DraggableModal } from '@/framework/components/core/draggable-modal';
import { Button, Popconfirm, message } from 'ant-design-vue';
import { CalendarOutlined } from '@ant-design/icons-vue';
import { VxeTableInstance } from 'vxe-table';
import { computed, reactive, ref, watch } from 'vue';
import {
  postSaveApproval,
  getApprovalName,
  getApprovalCode,
} from '@/modules/share-management/api/sample-sharing';
import { useRouter } from 'vue-router';

type State = {
  loading: boolean;
  tableData: any[];
  approvalSlipName: string;
  ApprovalSlipCode: string;
};
const router = useRouter();
const props = withDefaults(
  defineProps<{
    title?: string;
    showModal: boolean;
    data: any[];
  }>(),
  {
    title: '生成审批单',
    showModal: false,
  },
);
const emits = defineEmits<{
  (e: 'update:showModal', state: boolean): void;
}>();

/**
 * data
 */
const state: State = reactive({
  loading: false,
  tableData: [],
  approvalSlipName: '',
  ApprovalSlipCode: '',
});
watch(
  () => props.data,
  () => {
    state.tableData = props.data;
  },
  {
    deep: true,
    immediate: true,
  },
);
watch(
  () => props.showModal,
  () => {
    if (props.showModal) {
      getApprovalSlipInfoFn();
    }
  },
);

const xTable = ref<VxeTableInstance>();
/**
 * fn
 */
// 获取审批单信息
const getApprovalSlipInfoFn = async () => {
  const approvalSlipName = await getApprovalName();
  state.approvalSlipName = approvalSlipName.result;
  const ApprovalSlipCode = await getApprovalCode();
  state.ApprovalSlipCode = ApprovalSlipCode.result;
};

// 提交&&保存
const modalSaveFn = async (type) => {
  const params = [
    {
      batchNo: state.ApprovalSlipCode,
      commit: type,
      name: state.approvalSlipName,
      stocks: state.tableData.map((item) => ({
        checker: item.checker,
        comment: item.comment,
        couriers: item.couriers,
        destination: item.destination,
        stockInstanceId: item.id,
        usage: item.usage,
      })),
    },
  ];
  if (
    !params[0].stocks.every(
      (el) => el.couriers && el.couriers.split(/,|.|\/|;|,|、/).length >= 2,
    )
  ) {
    return message.warn('运出人员必填,且需要双人');
  }
  await postSaveApproval(params);
  message.success('保存成功！');
  await router.push({
    name: 'approvalOrderRecords',
  });
};
// 关闭
const modalCancelFn = () => {
  emits('update:showModal', false);
  state.ApprovalSlipCode = '';
  state.approvalSlipName = '';
};
</script>

<style lang="less">
.approval {
  height: 80px;
  padding: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  background-color: #efefef;
  border: 1px solid #ccc;

  p {
    text-decoration: underline;
    font-weight: 700;
    margin-bottom: 0px;
  }

  .approval-name {
    display: inline-block;
    height: 34px;
    padding: 0 30px;
    margin-right: 80px;
    background-color: #fff;
    line-height: 34px;
    border-radius: 3px;
  }
}
.partition {
  text-decoration: underline;
  font-weight: 700;
  margin: 10px;
  font-size: 14px;
}
</style>
